package dwetl.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class FactTable implements Serializable {
	private static final long serialVersionUID = -1523817140503260797L;
	private String table_name = null;
	private List<FactColumn> etl_columns = new ArrayList<FactColumn>();

	private List<DimTable> dtbls=new LinkedList<DimTable>();
	private String projectName;
	private boolean enable_dim_cache=true;

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	public FactTable() {
		super();
	}

	public FactTable(String table_name, List<FactColumn> etl_columns) {
		super();
		this.table_name = table_name;
		this.etl_columns = etl_columns;
	}

	public String getTable_name() {
		return table_name;
	}

	public void setTable_name(String table_name) {
		this.table_name = table_name;
	}

	public List<FactColumn> getEtl_columns() {
		return etl_columns;
	}

	public void setEtl_columns(List<FactColumn> etl_columns) {
		this.etl_columns = etl_columns;
	}

	@Override
	public String toString() {
		String rl= "FactTable [table_name=" + table_name + ", etl_columns=" + etl_columns + "]";
		for(DimTable dt : dtbls){
			rl+="\r\n"+dt.toString();
		}
		return rl;
	}


	public List<DimTable> getDimTables(){
		return this.dtbls;
	}

	public void setDimTables(List<DimTable> dimTables){
		this.dtbls=dimTables;
	}

	public FactColumn findAutoIdColumn(){
		List<FactColumn> etl_columns = this.getEtl_columns();
		for(FactColumn dc:etl_columns){
			if(dc.getIs_auto_id()){
				return dc;
			}
		}
		return null;
	}

	public JSONObject toJson(){
		JSONObject jo=new JSONObject();
		jo.put("table_name",this.getTable_name());
		if(this.getEtl_columns()!=null && this.getEtl_columns().size()>0){
			JSONArray ja=new JSONArray();
			for(FactColumn fc:this.getEtl_columns()){
				JSONObject joj=fc.toJson();
				ja.add(joj);
			}
			jo.put("etl_columns",ja);
		}

		if(dtbls!=null && dtbls.size()>0){
			JSONArray ja=new JSONArray();
			for(DimTable dt:dtbls){
				JSONObject joj=dt.toJson();
				ja.add(ja);
			}
			jo.put("dim_tables",ja);
		}

		JSONObject rljo=new JSONObject();
		rljo.put("fact_table",jo);
		if(this.getProjectName()!=null){
			rljo.put("project_name",this.getProjectName());
		}
		return rljo;
	}

	public boolean isEnable_dim_cache() {
		return enable_dim_cache;
	}

	public void setEnable_dim_cache(boolean enable_dim_cache) {
		this.enable_dim_cache = enable_dim_cache;
	}

}
